import { Actions, } from 'react-native-router-flux';
import { Tabs, Toast, Portal } from '@ant-design/react-native';

import axios from 'axios';
import store from '../store/store';
import request from './request'
import { path, removeData, saveData } from '../util/utils';


import * as ActionTypes from '../constants/constants.js';

axios.defaults.timeout = 999999
// axios.defaults.baseURL = "http://47.94.148.123:8009/api/v1/"
axios.defaults.baseURL = 'http://39.106.180.25:9091';
// axios.defaults.baseURL = 'http://h:8091';
const instance = axios.create({
  baseURL: 'http://39.106.180.25:9091',
  headers: { 'Content-Type': 'multipart/form-data' }
});


const api = {
  async get(url, data) {
    let res = await axios.get(url, {
      headers: {
        "Content-Type": "application/json"
      },
      params: {
        ...data,
      },
    });
    return new Promise((resolve, reject) => {
      if (res) {
        resolve(res);
      } else {
        Toast.info('请求失败', 1)
        reject(res);
      }
    })
  },
  async post(url, data, callback) {
    let res = await axios.post(url, data, { headers: { 'Content-Type': 'application/json' } });
    return new Promise((resolve, reject) => {
      if (!res) {
        Toast.info('请求失败', 1)
        reject()
        return
      }
      if (res.data.code == 200) {
        resolve(res.data);
      } else {
        callback ? callback(res.data) : Toast.info(res.data.message, 1)
        reject(res.data);
      }
    })
  },
  async upload(url, data) {
    let res = await instance.post(url, data, {});
    return new Promise((resolve, reject) => {
      if (res.data.code == 200) {
        resolve(res.data);
      } else {
        // Toast.info(res.data.message, 1)
        reject(res.data);
      }
    })
  },
};

axios.interceptors.request.use((request) => {
  // 在发送请求之前做些什么
  // console.log(`发起请求：path:${request.url}，baseURL:${request.baseURL}`)
  // console.log(`openid：${store.state.openId}`)
  // if (request.url != 'api/wx/getAuth') {
  //     let openid = store.state.openid
  //     console.log(`请求前添加openid：${store.state.openid}`)
  //     request.headers["openid"] = openid;
  // }
  // console.log(request, '发送请求')
  // if (request.url.indexOf('/upload') > -1) {
  //   console.log(request.headers, '图片上传')
  // } else {
  //   console.log('普通请求')
  //   request.headers['Content-Type'] = 'application/json'
  // }
  // request.data = JSON.stringify(request.data);
  // request.headers['Content-Type'] = 'application/json'
  let token = store.getState().token
  if (token) {
    request.headers["token"] = token
  }
  return request;
}, function (error) {
  // 对请求错误做些什么
  Toast.info('请求失败', 1)
  return Promise.reject(error);
});

instance.interceptors.request.use((request) => {
  // 在发送请求之前做些什么
  // console.log(`发起请求：path:${request.url}，baseURL:${request.baseURL}`)
  // console.log(`openid：${store.state.openId}`)
  // if (request.url != 'api/wx/getAuth') {
  //     let openid = store.state.openid
  //     console.log(`请求前添加openid：${store.state.openid}`)
  //     request.headers["openid"] = openid;
  // }
  // console.log(request, '发送请求')
  // if (request.url.indexOf('/upload') > -1) {
  //   console.log(request.headers, '图片上传')
  // } else {
  //   console.log('普通请求')
  //   request.headers['Content-Type'] = 'application/json'
  // }
  // request.data = JSON.stringify(request.data);
  // request.headers['Content-Type'] = 'application/json'
  let token = store.getState().token
  if (token) {
    request.headers["token"] = token
  }
  return request;
}, function (error) {
  // 对请求错误做些什么
  Toast.info('请求失败', 1)
  return Promise.reject(error);
});



axios.interceptors.response.use((response) => {
  if (response.data.code == 401) {
    // token 失效了
    // console.log('登录失效了')
    return request.refreshToken().then(token => {
      console.log(token, '刷新token')
      if (token.data) {
        const config = response.config
        store.dispatch({
          type: ActionTypes.setToken,
          data: token.data.token
        })
        // console.log('刷新token')
        Actions.mall()
        return axios(config)
      }
    }).catch(res => {
      // console.log('refreshtoken error =>', res)
      //刷新token失败，神仙也救不了了，跳转到首页重新登录吧
      // window.location.href = '/'
      Toast.info('登录失效', 1)
      store.dispatch({
        type: ActionTypes.clearToken
      })
      Actions.login({ type: "reset" })
    })
  }
  return response;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

instance.interceptors.response.use((response) => {
  if (response.data.code == 401) {
    // token 失效了
    // console.log('登录失效了')
    return request.refreshToken().then(token => {
      console.log(token, '刷新token')
      if (token.data) {
        const config = response.config
        store.dispatch({
          type: ActionTypes.setToken,
          data: token.data.token
        })
        // console.log('刷新token')
        Actions.mall({ type: "reset" })
        return instance(config)
      }
    }).catch(res => {
      // console.log('refreshtoken error =>', res)
      //刷新token失败，神仙也救不了了，跳转到首页重新登录吧
      // window.location.href = '/'
      Toast.info('登录失效', 1)
      store.dispatch({
        type: ActionTypes.clearToken
      })
      Actions.login({ type: "reset" })
    })
  }
  return response;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});




export default api;
